<?php
namespace LSYS\Area;
use LSYS\Area;

class GEO{
	public static $api="baidu";
	/**
	 * list($code,$area,$addr,$detail);
	 * 根据坐标获得城市信息
	 * @param string $lat
	 * @param string $lng
	 * @return boolean
	 */
	public static function geo_get_addr($lat,$lng){
		if(empty($lat)||empty($lng)) return false;
		$url="http://api.map.baidu.com/geocoder/v2/?ak=02da4fa06849ac43b362e2fd96ae09f3&location=$lat,$lng&output=json";
		$data=self::curl($url);
		$bad=array(null,null,null,array());
		if(empty($data)) return $bad;
		$data=json_decode($data,true);
		if($data['status']!=0) return $bad;
		if(empty($data['result']['addressComponent'])) return  $bad;
		$data=$data['result']['addressComponent'];
		$addr=isset($data['street'])?$data['street']:'';
		$addr.=isset($data['street_number'])?$data['street_number']:'';
		if ($data['country_code']=='0'){
			list($area,$detail)=Area::instance()->parse(Area::instance()->areacode_to_code(CN::$china_code.$data['adcode']));
			return array($data['adcode'],$area,$addr,$detail);
		}
		$area=isset($data['country'])?$data['country']:'';
		$area.=isset($data['province'])?' '.$data['province']:'';
		$area.=isset($data['city'])?' '.$data['city']:'';
		$area.=isset($data['district'])?' '.$data['district']:'';
		return array(isset($data['adcode'])?$data['adcode']:'0',trim($area),$addr,array());
	}
	protected static function curl($url){
		$s = curl_init();
		curl_setopt($s,CURLOPT_URL,$url);
		curl_setopt($s,CURLOPT_HTTPHEADER,array('Expect:'));
		curl_setopt($s,CURLOPT_TIMEOUT,10);
		curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($s,CURLOPT_USERAGENT,isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'GEO CLIENT');
		$ss= curl_exec($s);
		curl_close($s);
		return $ss;
	}
	
	
	public static function get_get_add_form_db($lat,$lng){
		$table=Area::db()->quote_table(Area::$table);
		$geohash=ddd::encode();
		$sql="select * from {$table} WHERE geohash LIKE '{$geohash}%'";
	}
	
}